<template>
  <el-dialog
    :model-value="visible"
    :title="dialogTitle"
    width="600px"
    @update:model-value="$emit('update:visible', $event)"
    @close="handleClose"
  >
    <el-form
      :model="fieldForm"
      :rules="readonly ? {} : fieldRules"
      ref="fieldFormRef"
      label-width="120px"
    >
      <el-form-item label="字段分类">
        <el-input
          v-model="fieldForm.fieldCategory"
          placeholder="请输入字段分类"
          :disabled="readonly"
        />
      </el-form-item>
      <el-form-item label="字段名称" prop="fieldName">
        <el-input
          v-model="fieldForm.fieldName"
          placeholder="请输入字段名称"
          :disabled="readonly"
          @blur="validateFieldName"
        />
      </el-form-item>
      <el-form-item label="字段英文名称" prop="fieldEnglishName">
        <el-input
          v-model="fieldForm.fieldEnglishName"
          placeholder="小写字母、下划线、数字组成，仅支持小写字母开头，20个字符以内"
          :disabled="readonly"
          @blur="validateEnglishName"
        />
      </el-form-item>
      <el-form-item label="字段类型" prop="fieldType">
        <el-select
          v-model="fieldForm.fieldType"
          placeholder="请选择字段类型"
          style="width: 100%"
          :disabled="readonly"
          @change="handleFieldTypeChange"
        >
          <el-option label="两位小数" :value="1" />
          <el-option label="整数" :value="2" />
          <el-option label="日期" :value="3" />
          <el-option label="文本" :value="4" />
          <el-option label="枚举" :value="5" />
        </el-select>
      </el-form-item>
      <!-- 枚举选项配置 -->
      <el-form-item
        v-if="fieldForm.fieldType === 5"
        label="选项配置"
        prop="enumOptions"
        :rules="[
          {
            required: true,
            message: '至少需要两个选项',
            trigger: 'blur',
            validator: validateEnumOptions
          }
        ]"
      >
        <div class="enum-options">
          <div
            v-for="(option, index) in fieldForm.enumOptions"
            :key="index"
            class="enum-option-item"
          >
            <el-input
              v-model="option.value"
              placeholder="请输入选项,内容不允许重复"
              :disabled="readonly"
              @blur="validateEnumOption(index)"
            />
            <el-button
              v-if="!readonly && fieldForm.enumOptions.length > 2"
              type="danger"
              :icon="Delete"
              circle
              @click="removeEnumOption(index)"
            />
            <el-button
              v-if="
                !readonly &&
                index === fieldForm.enumOptions.length - 1 &&
                fieldForm.enumOptions.length < 10
              "
              type="primary"
              :icon="Plus"
              circle
              @click="addEnumOption"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="是否必填" prop="isRequired">
        <el-select
          v-model="fieldForm.isRequired"
          placeholder="请选择"
          style="width: 100%"
          :disabled="readonly"
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="添加计算公式" prop="hasFormula">
        <el-select
          v-model="fieldForm.hasFormula"
          placeholder="请选择"
          style="width: 100%"
          :disabled="readonly"
          @change="handleFormulaChange"
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <!-- 计算公式配置 -->
      <el-form-item
        v-if="fieldForm.hasFormula"
        label="计算公式"
        prop="formula"
        :rules="[
          {
            required: true,
            message: '请配置计算公式',
            trigger: 'blur',
            validator: validateFormula
          }
        ]"
      >
        <div class="formula-config">
          <div class="formula-items">
            <el-select
              v-model="fieldForm.formula.leftField"
              placeholder="请选择使用字段"
              style="width: 150px"
              :disabled="readonly"
              @change="updateFormulaDisplay"
            >
              <el-option
                v-for="field in numericFields"
                :key="field.id || field.fieldEnglishName"
                :label="field.fieldName"
                :value="field.fieldName"
              />
            </el-select>
            <el-select
              v-model="fieldForm.formula.operator"
              placeholder="运算符"
              style="width: 100px"
              :disabled="readonly"
              @change="updateFormulaDisplay"
            >
              <el-option label="+" value="+" />
              <el-option label="-" value="-" />
              <el-option label="*" value="*" />
              <el-option label="/" value="/" />
            </el-select>
            <el-select
              v-model="fieldForm.formula.rightField"
              placeholder="请选择使用字段"
              style="width: 150px"
              :disabled="readonly"
              @change="updateFormulaDisplay"
            >
              <el-option
                v-for="field in numericFields"
                :key="field.id || field.fieldEnglishName"
                :label="field.fieldName"
                :value="field.fieldName"
              />
            </el-select>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-if="readonly" @click="handleClose">关闭</el-button>
      <template v-else>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'
import { getFieldId } from '@/api/system/materials'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  fieldList: {
    type: Array,
    default: () => []
  },
  fieldData: {
    type: Object,
    default: null
  },
  materialId: {
    type: [String, Number],
    required: true
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'success'])

const fieldFormRef = ref()
const dialogTitle = ref('添加字段')
const isEditField = ref(false)
const editingFieldId = ref(null)

const fieldForm = reactive({
  fieldCategory: '',
  fieldName: '',
  fieldEnglishName: '',
  fieldType: 4, // 默认文本
  enumOptions: [{ value: '' }, { value: '' }], // 枚举选项，至少两个
  isRequired: true, // 默认是
  hasFormula: false, // 默认否
  formula: {
    leftField: '',
    operator: '',
    rightField: ''
  }
})

// 字段表单验证规则
const fieldRules = {
  fieldName: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
  fieldEnglishName: [
    { required: true, message: '请输入字段英文名称', trigger: 'blur' },
    {
      pattern: /^[a-z][a-z0-9_]{0,19}$/,
      message: '小写字母、下划线、数字组成，仅支持小写字母开头，20个字符以内',
      trigger: 'blur'
    }
  ],
  fieldType: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
  isRequired: [{ required: true, message: '请选择是否必填', trigger: 'change' }],
  hasFormula: [{ required: true, message: '请选择是否添加计算公式', trigger: 'change' }]
}

// 计算属性：获取数值类型字段（用于计算公式）
const numericFields = computed(() => {
  return props.fieldList.filter((field) => {
    // 排除当前正在编辑的字段
    if (isEditField.value && field.id === editingFieldId.value) {
      return false
    }
    // 只包含数值类型字段
    return (
      field.fieldType === 1 || // 两位小数
      field.fieldType === 2 // 整数
    )
  })
})

// 监听 fieldData 变化，初始化编辑数据
watch(
  () => props.fieldData,
  (newData) => {
    if (newData && props.visible) {
      // 查看模式或编辑模式
      if (props.readonly) {
        dialogTitle.value = '查看详情'
        isEditField.value = false
      } else {
        dialogTitle.value = '编辑字段'
        isEditField.value = true
      }
      editingFieldId.value = newData.id

      // 填充表单数据
      fieldForm.fieldCategory = newData.fieldCategory || ''
      fieldForm.fieldName = newData.fieldName || ''
      fieldForm.fieldEnglishName = newData.fieldEnglishName || ''
      fieldForm.fieldType = newData.fieldType || 4
      fieldForm.isRequired = newData.isRequired !== undefined ? newData.isRequired : 1
      fieldForm.hasFormula = newData.isFormula || 0

      // 如果是枚举类型，填充枚举选项
      if (newData.fieldType === 5 && newData.enumOptions && Array.isArray(newData.enumOptions)) {
        fieldForm.enumOptions = newData.enumOptions.map((opt) => {
          // 如果选项是字符串，直接使用；如果是对象，取value
          return { value: typeof opt === 'string' ? opt : opt.value || opt }
        })
        if (fieldForm.enumOptions.length < 2) {
          fieldForm.enumOptions = [{ value: '' }, { value: '' }]
        }
      } else {
        fieldForm.enumOptions = [{ value: '' }, { value: '' }]
      }

      // 如果有计算公式，填充公式数据
      if (newData.isFormula && newData.formula) {
        // 解析公式，例如 "数量*单价"
        const formulaStr = newData.formula
        const operators = ['+', '-', '*', '/']
        let operator = ''
        for (const op of operators) {
          if (formulaStr.includes(op)) {
            operator = op
            break
          }
        }
        if (operator) {
          const [left, right] = formulaStr.split(operator)
          fieldForm.formula.leftField = left.trim()
          fieldForm.formula.operator = operator
          fieldForm.formula.rightField = right.trim()
        }
      } else {
        fieldForm.formula = {
          leftField: '',
          operator: '',
          rightField: ''
        }
      }
    } else if (props.visible && !newData) {
      // 添加模式
      dialogTitle.value = '添加字段'
      isEditField.value = false
      editingFieldId.value = null
      resetForm()

      // 获取字段ID
      getFieldId({ id: props.materialId })
        .then((res) => {
          if (res.data) {
            editingFieldId.value = res.data
          }
        })
        .catch((error) => {
          console.error('获取字段ID失败:', error)
        })
    }
  },
  { immediate: true }
)

// 监听 visible 变化，关闭时重置表单
watch(
  () => props.visible,
  (newVal) => {
    if (!newVal) {
      resetForm()
    }
  }
)

// 重置表单
function resetForm() {
  fieldForm.fieldCategory = ''
  fieldForm.fieldName = ''
  fieldForm.fieldEnglishName = ''
  fieldForm.fieldType = 4 // 默认文本
  fieldForm.enumOptions = [{ value: '' }, { value: '' }]
  fieldForm.isRequired = 1 // 默认是
  fieldForm.hasFormula = 0 // 默认否
  fieldForm.formula = {
    leftField: '',
    operator: '',
    rightField: ''
  }
  fieldFormRef.value?.clearValidate()
}

// 关闭弹窗
function handleClose() {
  emit('update:visible', false)
}

// 验证字段名称（同一字段分类下不允许重复）
function validateFieldName() {
  if (!fieldForm.fieldName) return

  const duplicate = props.fieldList.find((field) => {
    if (isEditField.value && field.id === editingFieldId.value) {
      return false // 编辑时排除自己
    }
    // 如果字段分类都为空，或者都相同，且字段名称相同，则重复
    const categoryMatch =
      (!field.fieldCategory && !fieldForm.fieldCategory) ||
      field.fieldCategory === fieldForm.fieldCategory
    return categoryMatch && field.fieldName === fieldForm.fieldName
  })

  if (duplicate) {
    ElMessage.error('同一字段分类下字段名称不允许重复')
    fieldFormRef.value?.validateField('fieldName', () => {})
  }
}

// 验证字段英文名称（同一物料字段内不允许重复）
function validateEnglishName() {
  if (!fieldForm.fieldEnglishName) return

  const duplicate = props.fieldList.find((field) => {
    if (isEditField.value && field.id === editingFieldId.value) {
      return false // 编辑时排除自己
    }
    return field.fieldEnglishName === fieldForm.fieldEnglishName
  })

  if (duplicate) {
    ElMessage.error('同一物料字段内英文名称不允许重复')
    fieldFormRef.value?.validateField('fieldEnglishName', () => {})
  }
}

// 验证枚举选项
function validateEnumOptions(rule, value, callback) {
  const validOptions = fieldForm.enumOptions.filter((opt) => opt.value && opt.value.trim())
  if (validOptions.length < 2) {
    callback(new Error('至少需要两个选项'))
    return
  }

  // 检查是否有重复
  const values = validOptions.map((opt) => opt.value.trim())
  const uniqueValues = new Set(values)
  if (uniqueValues.size !== values.length) {
    callback(new Error('选项不允许重复'))
    return
  }

  callback()
}

// 验证单个枚举选项（不允许重复）
function validateEnumOption(index) {
  const currentValue = fieldForm.enumOptions[index].value?.trim()
  if (!currentValue) return

  const duplicateIndex = fieldForm.enumOptions.findIndex(
    (opt, idx) => idx !== index && opt.value?.trim() === currentValue
  )

  if (duplicateIndex !== -1) {
    ElMessage.error('选项不允许重复')
    fieldForm.enumOptions[index].value = ''
  }
}

// 添加枚举选项
function addEnumOption() {
  if (fieldForm.enumOptions.length < 10) {
    fieldForm.enumOptions.push({ value: '' })
  } else {
    ElMessage.warning('最多只能添加10个选项')
  }
}

// 删除枚举选项
function removeEnumOption(index) {
  if (fieldForm.enumOptions.length > 2) {
    fieldForm.enumOptions.splice(index, 1)
  } else {
    ElMessage.warning('至少需要保留两个选项')
  }
}

// 验证计算公式
function validateFormula(rule, value, callback) {
  if (
    !fieldForm.formula.leftField ||
    !fieldForm.formula.operator ||
    !fieldForm.formula.rightField
  ) {
    callback(new Error('请完整配置计算公式'))
    return
  }
  callback()
}

// 处理字段类型变化
function handleFieldTypeChange(value) {
  // 如果切换到枚举类型，初始化枚举选项
  if (value === 5) {
    if (fieldForm.enumOptions.length === 0) {
      fieldForm.enumOptions = [{ value: '' }, { value: '' }]
    }
  }
}

// 处理计算公式选项变化
function handleFormulaChange(value) {
  // 如果选择不添加计算公式，清空公式配置
  if (!value) {
    fieldForm.formula = {
      leftField: '',
      operator: '',
      rightField: ''
    }
  }
}

// 更新公式显示
function updateFormulaDisplay() {
  // 可以在这里添加公式预览逻辑
}

// 保存字段
async function handleSave() {
  await fieldFormRef.value?.validate()

  // 验证字段名称重复性
  const duplicateName = props.fieldList.find((field) => {
    if (isEditField.value && field.id === editingFieldId.value) {
      return false
    }
    // 如果字段分类都为空，或者都相同，且字段名称相同，则重复
    const categoryMatch =
      (!field.fieldCategory && !fieldForm.fieldCategory) ||
      field.fieldCategory === fieldForm.fieldCategory
    return categoryMatch && field.fieldName === fieldForm.fieldName
  })

  if (duplicateName) {
    ElMessage.error('同一字段分类下字段名称不允许重复')
    return
  }

  // 验证字段英文名称重复性
  const duplicateEnglishName = props.fieldList.find((field) => {
    if (isEditField.value && field.id === editingFieldId.value) {
      return false
    }
    return field.fieldEnglishName === fieldForm.fieldEnglishName
  })

  if (duplicateEnglishName) {
    ElMessage.error('同一物料字段内英文名称不允许重复')
    return
  }

  // 验证枚举选项
  if (fieldForm.fieldType === 5) {
    const validOptions = fieldForm.enumOptions.filter((opt) => opt.value && opt.value.trim())
    if (validOptions.length < 2) {
      ElMessage.error('枚举类型至少需要两个选项')
      return
    }

    const values = validOptions.map((opt) => opt.value.trim())
    const uniqueValues = new Set(values)
    if (uniqueValues.size !== values.length) {
      ElMessage.error('枚举选项不允许重复')
      return
    }
  }

  // 验证计算公式
  if (fieldForm.hasFormula) {
    if (
      !fieldForm.formula.leftField ||
      !fieldForm.formula.operator ||
      !fieldForm.formula.rightField
    ) {
      ElMessage.error('请完整配置计算公式')
      return
    }
  }

  // 构建字段数据
  const fieldData = {
    id: editingFieldId.value,
    fieldCategory: fieldForm.fieldCategory || '',
    fieldName: fieldForm.fieldName,
    fieldEnglishName: fieldForm.fieldEnglishName,
    fieldType: fieldForm.fieldType,
    isRequired: fieldForm.isRequired,
    isFormula: fieldForm.hasFormula,
    serialNumber: isEditField.value
      ? props.fieldList.find((f) => f.id === editingFieldId.value)?.serialNumber ||
        props.fieldList.length + 1
      : props.fieldList.length + 1
  }

  // 如果是枚举类型，添加枚举选项
  if (fieldForm.fieldType === 4) {
    fieldData.enumOptions = fieldForm.enumOptions
      .filter((opt) => opt.value && opt.value.trim())
      .map((opt) => opt.value.trim())
  }

  // 如果有计算公式，构建公式字符串
  if (fieldForm.hasFormula) {
    // 使用中文名称构建公式
    if (fieldForm.formula.leftField && fieldForm.formula.operator && fieldForm.formula.rightField) {
      fieldData.formula = `${fieldForm.formula.leftField}${fieldForm.formula.operator}${fieldForm.formula.rightField}`
    }
  }

  // 触发成功事件
  emit('success', fieldData, isEditField.value)
  handleClose()
}
</script>

<style lang="scss" scoped>
.enum-options {
  width: 100%;
}

.enum-option-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;

  .el-input {
    flex: 1;
  }

  .el-button {
    flex-shrink: 0;
  }
}

.formula-config {
  width: 100%;

  .formula-items {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }
}
</style>
